package com.yy.wga.user.service.listener;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yy.wga.common.dto.BaseRequestDTO;
import com.yy.wga.common.enmus.EProfilesType;
import com.yy.wga.common.interceptor.RequestUserHolder;
import com.yy.wga.user.service.pojo.UserBaseDO;
import com.yy.wga.user.service.pojo.UserRelationDO;
import com.yy.wga.user.service.pojo.UserWechatDO;
import com.yy.wga.module.user.enums.EUserGrade;
import com.yy.wga.module.user.events.FirstBuyUpgradeEvent;
import com.yy.wga.module.user.service.UserBaseService;
import com.yy.wga.module.user.service.UserRelationService;
import com.yy.wga.module.user.service.UserWechatService;
import com.yy.wga.module.wechat.feign.WechatMpFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: gc
 * @Date: 2024/11/27
 * @Description:
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class FirstBuyUpgradeListener implements ApplicationListener<FirstBuyUpgradeEvent> {

    @Value("${spring.profiles.active}")
    private String profiles;

    private final UserWechatService userWechatService;
    private final UserRelationService userRelationService;
    private final WechatMpFeign wechatMpFeign;
    private final UserBaseService userBaseService;

    @Async
    public void onApplicationEvent(FirstBuyUpgradeEvent event) {
        // 给上级发订阅消息
        UserRelationDO userRelation = userRelationService.getOne(new LambdaQueryWrapper<UserRelationDO>()
                .eq(UserRelationDO::getAppKey, event.getAppKey())
                .eq(UserRelationDO::getUserId, event.getUserId()));
        if (userRelation == null) {
            return;
        }
        this.sendMsg(userRelation.getParentUserId(), event);
        log.info("上级{}订阅通知", userRelation.getParentUserId());
        // 如果上级是服务商，不用重复通知了
        if (userRelation.getParentGrade().equals(EUserGrade.SERVER_1.getType())) {
            return;
        }

        // 获取服务商
        Long userId = userRelation.getParentUserId();
        while (true) {
            userRelation = userRelationService.getOne(new LambdaQueryWrapper<UserRelationDO>()
                    .eq(UserRelationDO::getAppKey, event.getAppKey())
                    .eq(UserRelationDO::getUserId, userId));
            if (userRelation == null) {
                return;
            }
            if (userRelation.getParentGrade().equals(EUserGrade.SERVER_1.getType())) {
                this.sendMsg(userRelation.getParentUserId(), event);
                log.info("服务商{}订阅通知", userRelation.getParentUserId());
                return;
            }
            userId = userRelation.getParentUserId();
        }
    }

    /**
     * 发送订阅消息
     *
     * @param userId
     * @param event
     */
    private void sendMsg(Long userId, FirstBuyUpgradeEvent event) {
        UserWechatDO userWechat = userWechatService.getByUserId(event.getAppKey(), event.getUserId());
        if (userWechat == null) {
            log.info("没有找到微信信息");
            return;
        }
        UserBaseDO userBaseDO = userBaseService.getOne(new LambdaQueryWrapper<UserBaseDO>()
                .eq(UserBaseDO::getAppKey, event.getAppKey())
                .eq(UserBaseDO::getId, event.getUserId()));
        WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
        wxMaSubscribeMessage.setTemplateId("yTP0tk3uFUrHCRJjrDWmZQ9m5v99yZ2MyXLED8nKDAU");
        wxMaSubscribeMessage.setToUser(userWechat.getOpenId());
        List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
        WxMaSubscribeMessage.MsgData msgData = new WxMaSubscribeMessage.MsgData();
        msgData.setName("thing1");
        msgData.setValue(userBaseDO.getNickName());
        dataList.add(msgData);
        msgData = new WxMaSubscribeMessage.MsgData();
        msgData.setName("thing2");
        EUserGrade userGrade = EUserGrade.getByType(userBaseDO.getGrade(), userBaseDO.getLevel());
        msgData.setValue(userGrade.getDesc());
        dataList.add(msgData);
        msgData = new WxMaSubscribeMessage.MsgData();
        msgData.setName("time3");
        msgData.setValue(DateUtil.format(event.getUpgradeTime(), DatePattern.NORM_DATETIME_MINUTE_PATTERN));
        dataList.add(msgData);
        wxMaSubscribeMessage.setData(dataList);
        // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        if (profiles.equals(EProfilesType.PRO.getProfiles())) {
            wxMaSubscribeMessage.setMiniprogramState("formal");
        } else {
            wxMaSubscribeMessage.setMiniprogramState("trial");
        }
        wxMaSubscribeMessage.setLang("zh_CN");
        try {
            BaseRequestDTO baseRequestDTO = new BaseRequestDTO();
            baseRequestDTO.setAppKey(event.getAppKey());
            RequestUserHolder.setBaseRequest(baseRequestDTO);
            wechatMpFeign.sendSubscribeMsg(wxMaSubscribeMessage);
        } finally {
            RequestUserHolder.removeBaseRequest();
        }
    }
}
